﻿#include "optioneditor.h"
#include "ui_optioneditor.h"

OptionEditor::OptionEditor(QWidget *parent, const QString &type) :
    BaseEditorDialog(parent),_type(type),
    ui(new Ui::OptionEditor)
{
    ui->setupUi(this);

    table = TD_OPTIONS;
    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);

    updateView();
    createMenu();
}

OptionEditor::~OptionEditor()
{
    delete ui;
}

void OptionEditor::createMenu()
{
    menu=new QMenu(this);

    menu->addAction(QStringLiteral("更新"),this,&OptionEditor::updateView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("撤销"),this,&OptionEditor::revert);
    menu->addAction(QStringLiteral("保存"),this,&OptionEditor::save);
    menu->addSeparator();
    menu->addAction(QStringLiteral("删除"),this,&OptionEditor::removeItem);
}

void OptionEditor::updateView()
{
    model->setTable(table);
    model->setFilter(QString("type = '%1'").arg(_type));
    model->select();

    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("选项"));    //label
    ui->tableView->hideColumn(2);   //type
}

/*
void OptionEditor::on_btn_add_clicked()
{
    int row=model->rowCount();
    if(row == 0)
        return;

    QModelIndex last=model->index(row - 1);
    QString lastStr=model->data(last,0).toString();
    if(lastStr == OPT_TEXT)
        return;

    model->insertRow(row);
    QModelIndex index=model->index(row);
    model->setData(index,OPT_TEXT);

    ui->listView->setCurrentIndex(index);
    ui->listView->edit(index);
    saveFlag=-1;
}
*/

void OptionEditor::removeItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}

bool OptionEditor::addItem(const QString &label)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (label,type) values (?,?)").arg(table));
    query.addBindValue(label);
    query.addBindValue(_type);
    return query.exec();
}

void OptionEditor::on_btn_submit_clicked()
{
    QString item=ui->item->text().trimmed();
    if(item.isEmpty())
        return;

    if(addItem(item))
    {
        ui->item->clear();
        updateView();
    }
}
